
export default class IpcMgr {
  /**
   * 主进程进程通信辅助类
   * @param {object} listener 监听
   * @param {object} sender 发送
   * @param {string} channelOn 监听通道
   * @param {string} channelSend 发送通道
   * @param {Array} handlers 添加处理方法，[(ipc)=>{}]
   */
  constructor (listener, sender, channelOn, channelSend, handlers = []) {
    this.listener = listener
    this.sender = sender
    this.channel = { channelOn, channelSend }
    // 生成方法字典
    this.handlerList = Object.assign({}, ...handlers.map(f => f(this)))
    // 添加监听分发
    this.listener.on(channelOn, (event, data) => {
      try {
        const r = this.handlerList[data.type](event, data.data)
        if (!r) return
        if (r.type && r.data) {
          this.send(r.type, r.message)
        } else if (typeof r === 'string') {
          this.message(r)
        } else {
          this.send(data.type, r)
        }
      } catch (error) {
        console.error('handler event error:' + error.message)
      }
    })
  }

  send (type, data) {
    this.sender.send(
      this.channel.channelSend,
      {
        type,
        data
      }
    )
  }

  message (data) {
    this.send('message', data)
  }
}
